﻿using System;
using System.Collections.Generic;
using System.Text;
using Android.App;
using Android.Util;
using Java.IO;
using Java.Net;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;
using System.Threading.Tasks;

//using Android.Net.Http;

namespace NetDemo.android.Class
{
    public class UpdateManager
    {
        static string ApkSavePath = "";

        private const int Downloading = 1;
        private const int DownloadFinish = 2;

        static int progress = 0;
        private bool cancelUpdate = false;

        static Context MContext;

        static ProgressDialog PogressDlg = null;

        

        private String updateMsg = "有最新的软件包,是否更新?";

        private Dialog NoticeDialog = null;
        static Dialog DownloadingDialog = null;

        static ProgressBar mProgress;

        public Handler MessageHandler = new Handler(OnMsgHandler);

        private static void OnMsgHandler(Message msg)
        {
            //throw new NotImplementedException();
            switch (msg.What)
            {
                case Downloading:
                    Log.Debug("Info:", "Info: get downloading msg: progress" + progress);
                   // PogressDlg.Progress = progress;
                    mProgress.Progress = progress;
                    break;
                case DownloadFinish:
                    Log.Debug("Info:", "Info:Completed downloading. to installing");

                    InstallApk();
                    break;
                default:
                    break;
            }
        }

        private static void InstallApk()
        {
            try
            {
                DownloadingDialog.Dismiss();
             
                File apkFile = new File(ApkSavePath);
                if (!apkFile.Exists())
                {
                    return;
                }
                Intent i = new Intent(Intent.ActionView);
                //Uri uri=new Uri("file://"+apkFile.ToString());
                Android.Net.Uri uri = Android.Net.Uri.Parse("file://" + apkFile.ToString());
                i.SetDataAndType(uri, "application/vnd.android.package-archive");
                MContext.StartActivity(i);
                
            }
            catch (Exception e)
            {
                Log.Debug("Error:", e.Message + "|" + e.StackTrace);
            }

        }

        public UpdateManager(Context context)
        {
            //PogressDlg = progressDialog;
            //MessageHandler = msgHandler;
            MContext = context;
        }

        private void StartDownload()
        {
            Task.Factory.StartNew(Download);
        }

        public void CheckAndUpdate()
        {
            ShowNoticeDialog();
        }

        void ShowNoticeDialog()
        {
            try
            {
                AlertDialog.Builder dlg = new AlertDialog.Builder(MContext);
                dlg.SetTitle("软件更新");
                dlg.SetMessage(updateMsg);
                dlg.SetPositiveButton("下载", new EventHandler<DialogClickEventArgs>(OnDownloadClick));// (dia, witch) => { OnDownloadClick(dia,witch); });
                dlg.SetNegativeButton("以后再说", new EventHandler<DialogClickEventArgs>(OnDownloadCancel));

                NoticeDialog = dlg.Create();
                NoticeDialog.Show();
            }
            catch (Exception e)
            {
                Log.Debug("Error:", e.Message + "|" + e.StackTrace);
            }
        }

        void OnDownloadClick(object s, DialogClickEventArgs e)
        {
            var dlg = s as Dialog;
            dlg.Dismiss();
            ShowDownloadDialog();
        }

        void OnDownloadCancel(object s, DialogClickEventArgs e)
        {
            ((Dialog)s).Dismiss();
        }


        private void ShowDownloadDialog()
        {
            try
            {
                AlertDialog.Builder dlg = new AlertDialog.Builder(MContext);
                dlg.SetTitle("软件更新");

                LayoutInflater inflater = LayoutInflater.From(MContext);
                View v = inflater.Inflate(Resource.Layout.Progress, null);
                mProgress = v.FindViewById<ProgressBar>(Resource.Id.progress);

                dlg.SetView(v);
                dlg.SetNegativeButton("取消", new EventHandler<DialogClickEventArgs>(OnDownloadCaceled));

                DownloadingDialog = dlg.Create();
                DownloadingDialog.Show();

                StartDownload();
            } 
            catch (Exception e)
            {
                Log.Debug("Error:", e.Message + "|" + e.StackTrace);
            }
        }

        private void OnDownloadCaceled(object sender, DialogClickEventArgs e)
        {
            ((Dialog)(sender)).Dismiss();
            cancelUpdate = true;
        }

        private void Download()
        {

            // var client = AndroidHttpClient.NewInstance("Android");
            //client.
            if (Android.OS.Environment.ExternalStorageState.Equals(Android.OS.Environment.MediaMounted))
            {
                Log.Debug("Info:", "Info,Get the storage path");
                var sdcardPath = Android.OS.Environment.ExternalStorageDirectory + "/";
                ApkSavePath = sdcardPath + "download";

                File file = new File(ApkSavePath);
                if (!file.Exists())
                {
                    file.Mkdir();
                }
                if (file.Exists())
                {
                    file.Delete();
                }

                Log.Debug("Info:", "Info,The path is : "+ApkSavePath);

                File ApkFile = new File(ApkSavePath, "baidumap_andr_3052.apk");

                var url = "http://shouji.baidu.com/download/map/3052/baidumap_andr_3052.apk";

                var downUrl = new URL(url);

                //var inputStream = downUrl.OpenStream();

                HttpURLConnection conn = (HttpURLConnection)downUrl.OpenConnection();
                conn.Connect();
                var totalLength = conn.ContentLength;
                Log.Debug("INFO: ","TotalLength=" + totalLength);

                var inputStream = conn.InputStream;

                int readingCount = 0;

                byte[] buffer = new byte[1024];
                int readNum = 0;

                var fos = new FileOutputStream(ApkFile);

                while ((readNum = inputStream.Read(buffer, 0, buffer.Length)) > 0 && !cancelUpdate)
                {
                    readingCount += readNum;
                    progress = (int)(((float)readingCount / totalLength) * 100);
                   // mProgress.Progress=progress;
                    
                    MessageHandler.SendEmptyMessage(Downloading);
                    fos.Write(buffer, 0, readNum);
                }

                if (!cancelUpdate)
                {
                    MessageHandler.SendEmptyMessage(DownloadFinish);
                }

            }
        }
    }
}
